import Vue from 'vue';
import VueRouter from 'vue-router';
import cookieUtil from '@/utils/cookie.js';
import commonUtil from '@/utils/common.js';
// import watermark from '../utils/waterMarks.js'
/*
 * import { _ } from 'vue-underscore';
 * import axios from 'axios';
 */

const Login = () => import( /* webpackChunkName: "basic" */ '@/views/login/index');

const Findpw = () => import( /* webpackChunkName: "basic" */ '@/views/login/findpw');
const Main = () => import( /* webpackChunkName: "basic" */ '@/views/chnlayout/layout');
const OuterSpace = () => import( /* webpackChunkName: "basic" */ '@/components/404.vue');


/*
 * 后面新增组件按模块, webpackChunkName: '模块名', 进行路由懒加载约定，添加路由时注意。
 * 像，结算模块的所有组件，使用webpackChunkName: 'settleModule'等。
 * 如果是iframe的话，组件component 换成 iframeComponent
 */


const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err);
};

Vue.use(VueRouter);

export let asyncRoutes = [{
	path: '/',
	redirect: '/main/page'
}, {
	path: '/main',
	component: Main,
	children: [
		{
			path: 'page',
			component: () => import( /* webpackChunkName: "recruit" */ '@/views/chnlayout/content.vue'),
			meta: { requireAuth: true }
		},
		{
			path: 'auth',
			component: () => import( /* webpackChunkName: "recruit" */ '@/views/auth.vue'),
			meta: { requireAuth: true }
		},
		{
			path: 'authView',
			component: () => import( /* webpackChunkName: "recruit" */ '@/views/authView.vue')
		},
		{
			path: 'test1',
			component: () => import( /* webpackChunkName: "recruit" */ '@/views/test1.vue')
		},
		{
			path: 'test2',
			component: () => import( /* webpackChunkName: "recruit" */ '@/views/test2.vue')
		},
	]
},
{
	path: '/notFound',
	component: OuterSpace,
	meta: { requireAuth: false }
},
{
	path: '/login',
	component: Login,
	meta: { requireAuth: false }
},
{
	path: '/findpw',
	component: Findpw,
	meta: { requireAuth: false }
}
];

const router = new VueRouter({
	mode: 'hash',
	routes: asyncRoutes
});

router.beforeEach((to, from, next) => {
	if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
		if (cookieUtil.getCookie('track_token')) { // 通过vuex state获取当前的user是否存在
			next();
		} else {
			const urlParams = new URLSearchParams(window.location.search);
			const track_token = urlParams.get('track_token') || to.query.track_token;
			if (track_token) {
				cookieUtil.setCookie('track_token', track_token);
				next();
			} else {
				next({
					path: '/login',
					query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
				});
			}
		}
	} else {
		next();
	}
});

/*
 * router.afterEach((to) => {
 *     const urlParams = new URLSearchParams(window.location.search);
 *     const track_token = urlParams.get('track_token') || to.query.track_token;
 *     const trackToken = commonUtil.getQueryVariable(window.location.search, 'track_token');
 *     // alert(track_token)
 *     if(track_token){
 *         // let url = window.location.href;
 *         // const subStr = url.substring(url.indexOf("?"), url.indexOf("#"));
 *         // url = url.replaceAll(subStr,"")
 *         // console.log('url:',url);
 *         // window.location.href = url;
 *         cookieUtil.setCookie('track_token', track_token)
 *     }else{
 */

/*
 *     }
 * })
 */


/*
 * router.afterEach((to) => {
 *     window.localStorage.setItem('currentRouter', to.fullPath);
 *     let accessToken = to.query.access_token || localStorage.getItem('access_token');
 *     if (accessToken != 'undefined' && accessToken != undefined && accessToken != '' && accessToken != null){
 *         window.localStorage.setItem('access_token', accessToken);
 *         asyncRoutes.forEach(element => {
 *             if (element.path == '/main') {
 *                 let pageIndex = element.children.findIndex(v=>v.path=='page');
 *                 if (pageIndex==-1){ 
 *                     element.children.push({
 *                         path: 'page',
 *                         component: () =>
 *                             import('@/views/chnlayout/content.vue')
 *                     });
 *                 }
 *             }
 *         });
 *     }else{
 *         asyncRoutes.forEach((element,index) => {
 *             if (element.path == '/main') {
 *                 element.children.forEach(child=>{
 *                     if (child.path=='page'){
 *                         element.children.splice(index,1);
 *                     }
 *                 })
 *             }
 *         });
 *     }
 *     for (let i = 0; i < asyncRoutes.length; i++) {
 *         const addRoute = asyncRoutes[i]
 *         router.addRoute(addRoute)
 *     }
 *     if (to.path !== '/login' && to.path !== '/main/page') {
 *         let userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
 *         let showInfo = '';
 *         if(userInfo.employeeName!=undefined && userInfo.employeeName!=null && userInfo.employeeName!=''){
 *             showInfo += userInfo.employeeName;
 *         }
 *         if(userInfo.username!=undefined && userInfo.username!=null && userInfo.username!=''){
 *             showInfo += userInfo.username;
 *         }
 * 	    // watermark.set(showInfo)
 * 	}
 * });
 */

export default router;
